package com.ca.ridersclubapplication;

import android.app.Dialog;
import android.content.ContentUris;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.activity.result.ActivityResultCallback;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.ca.ridersclubapplication.data.DataHandler;
import com.ca.ridersclubapplication.data.entity.Handleable;
import com.ca.ridersclubapplication.request.AccountRequester;
import com.ca.ridersclubapplication.request.AfterExecutor;
import com.ca.ridersclubapplication.request.FileRequester;
import com.ca.ridersclubapplication.request.dto.AccountDto;
import com.ca.ridersclubapplication.request.dto.AccountUpdateDto;
import com.ca.ridersclubapplication.request.dto.Result;
import com.ca.ridersclubapplication.util.ImageUtils;
import com.ca.ridersclubapplication.view.CallbackView;
import com.ca.ridersclubapplication.view.input.GenderSelector;
import com.ca.ridersclubapplication.view.input.InfoItem;
import com.ca.ridersclubapplication.view.input.TextValueEdit;
import com.dylanc.activityresult.launcher.CropPictureLauncher;
import com.dylanc.activityresult.launcher.GetContentLauncher;
import com.dylanc.activityresult.launcher.GetMultipleContentsLauncher;

public class UpdateActivity extends ImmersiveActivity {

    public static final int PICK_PHOTO = 102;

    private AccountUpdateDto dto = null;

    private ImageView backButton;

    private ImageView headerImageView;
    private ImageView headerButton;

    private InfoItem nicknameItem;
    private InfoItem genderItem;
    private InfoItem birthItem;
    private InfoItem profileItem;

    private ConstraintLayout processCL;


    //  用于打开相册的启动器
    private GetContentLauncher launcher;
    private CropPictureLauncher cropPictureLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update);

        //  初始化视图
        initView();

        //  加载数据
        loadData();
    }

    private void initView() {

        backButton = findViewById(R.id.btn_back);

        headerImageView = findViewById(R.id.iv_header);
        headerButton = findViewById(R.id.btn_header);

        nicknameItem = findViewById(R.id.info_nickname);
        genderItem = findViewById(R.id.info_gender);
        birthItem = findViewById(R.id.info_birth);
        profileItem = findViewById(R.id.info_profile);

        //  设置标签
        nicknameItem.labelView.setText("昵称");
        genderItem.labelView.setText("性别");
        birthItem.labelView.setText("生日");
        profileItem.labelView.setText("简介");

        //  加载头像
        Long accountId = DataHandler.getToken(this).getId();
        ImageUtils.loadCircleImage(this, FileRequester.HEADER_BY_ID_BASE_URL + accountId, headerImageView);


        processCL = findViewById(R.id.cl_process);

        DataHandler.putView("AccountUpdateDto:" + accountId, new CallbackView() {
            @Override
            public void update() {
                Handleable handleable = DataHandler.getData("AccountUpdateDto:" + accountId);
                if (handleable instanceof AccountUpdateDto) {
                    AccountUpdateDto dto = (AccountUpdateDto) handleable;
                    nicknameItem.valueView.setText(dto.getNickname());
                    genderItem.valueView.setText(dto.getGender());
                    if (dto.getBirth() == null) {
                        birthItem.valueView.setText("无");
                    }
                    else {
                        birthItem.valueView.setText(dto.getBirth().substring(0, dto.getBirth().indexOf(" ")));
                    }
                    profileItem.valueView.setText(dto.getProfile());
                }
            }
        });

        //  用于打开相册的启动器
        launcher = new GetContentLauncher(this);
        cropPictureLauncher = new CropPictureLauncher(this);
    }

    private void initListener() {
        //  设置头像按钮点击事件
        headerButton.setOnClickListener(view -> {
            //  打开相册
            launcher.launchForImage(
                    result -> {

                        if (result == null) {
                            return;
                        }

                        //  裁切图片
                        cropPictureLauncher.launch(result, uri -> {

                            if (uri == null) {
                                return;
                            }

                            // 根据系统版本的不同，解析Uri（获取可用的路径）
                            String path;

                            if (Build.VERSION.SDK_INT > 21) {
                                // 4.4及以上系统使用这个方法处理图片
                                path = handleImageOnKitKat(uri);
                            } else {
                                // 4.4以下系统使用这个方法处理图片
                                path = getImagePath(uri, null);
                            }

                            FileRequester.uploadHeaderImage(UpdateActivity.this, path, new AfterExecutor<String>() {
                                @Override
                                public void execute(Result<String> result) {
                                    if (result.isSuccess()) {
                                        ImageUtils.loadCircleImage(
                                                UpdateActivity.this,
                                                FileRequester.HEADER_BY_ID_BASE_URL + dto.getId(),
                                                headerImageView);

                                        DataHandler.putData(dto);
                                    }
                                }
                            });
                        });
                    },
                    settingsLauncher -> {
                        // 用户始终拒绝了权限请求
                        Toast.makeText(this, "请允许访问相册", Toast.LENGTH_SHORT).show();
                        settingsLauncher.launch();
                    },
                    () -> {
                        // 用户拒绝了一次权限请求，提示用户
                        Toast.makeText(this, "请允许访问相册", Toast.LENGTH_SHORT).show();
                    }
            );
        });

        //  设置性别项点击事件
        genderItem.setOnClickListener(v -> {
            GenderSelector selector = new GenderSelector(this, this, dto, dto.getGender());
            Dialog genderDialog = new Dialog(this);
            selector.dialog = genderDialog;

            genderDialog.setContentView(selector);
            Window window = genderDialog.getWindow();
            WindowManager.LayoutParams attributes = window.getAttributes();
            attributes.width = WindowManager.LayoutParams.MATCH_PARENT;
            genderDialog.show();
        });

        //  设置昵称点击
        nicknameItem.setOnClickListener(v -> {

            TextValueEdit edit = new TextValueEdit(this, "nickname", this, dto);
            Dialog dialog = new Dialog(this);
            edit.dialog = dialog;

            dialog.setContentView(edit);
            Window window = dialog.getWindow();
            WindowManager.LayoutParams attributes = window.getAttributes();
            attributes.width = WindowManager.LayoutParams.MATCH_PARENT;
            dialog.show();
        });

        //  设置简介点击
        profileItem.setOnClickListener(v -> {
            TextValueEdit edit = new TextValueEdit(this, "profile", this, dto);
            Dialog dialog = new Dialog(this);
            edit.dialog = dialog;

            dialog.setContentView(edit);
            Window window = dialog.getWindow();
            WindowManager.LayoutParams attributes = window.getAttributes();
            attributes.width = WindowManager.LayoutParams.MATCH_PARENT;
            dialog.show();
        });

        //  日期选择对话框
        View ddp = getLayoutInflater().inflate(R.layout.dialog_date_picker, null);
        Dialog ddpDialog = new Dialog(this);
        ddpDialog.setContentView(ddp);
        //  设置生日按钮点击事件
        birthItem.setOnClickListener(v -> {
            ddpDialog.show();
        });
        //  日期选择事件
        DatePicker dp = ddp.findViewById(R.id.dp);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            dp.setOnDateChangedListener((view, year, monthOfYear, dayOfMonth) -> {
                String text = year + "-" + ((monthOfYear + 1) <= 9 ? "0" + (monthOfYear + 1) : (monthOfYear + 1)) + "-" + (dayOfMonth <= 9 ? "0" + dayOfMonth : dayOfMonth);
//                birthButton.setText(text);
                birthItem.valueView.setText(text);
                dto.setBirth(text + " 00:00:00");
                //  更新数据
                update(dto);
                ddpDialog.dismiss();
            });
        }

        //  返回按钮点击
        backButton.setOnClickListener(view -> {
            finishAfterTransition();
        });
    }

    private void loadData() {

        //  请求账号数据
        AccountRequester.getAccount(this, DataHandler.getToken(this).getId(), new AfterExecutor<AccountDto>() {
            @Override
            public void execute(Result<AccountDto> result) {

                AccountDto data = result.getData();
                if (result.isSuccess() && data != null) {
                    //  初始化监听器
                    initListener();
                    processCL.setVisibility(View.GONE);

                    //  设置视图数据
                    nicknameItem.valueView.setText(data.getNickname());
                    genderItem.valueView.setText(data.getGender());
                    String birth = data.getBirth();
                    if (birth == null) {
                        birthItem.valueView.setText("无");
                    }
                    else {
                        birthItem.valueView.setText(data.getBirth().substring(0, data.getBirth().indexOf(" ")));
                    }
                    profileItem.valueView.setText(data.getProfile());

                    //  设置数据
                    dto = AccountUpdateDto
                            .builder()
                            .id(data.getId())
                            .nickname(data.getNickname())
                            .gender(data.getGender())
                            .birth(data.getBirth())
                            .city("")
                            .profile(data.getProfile())
                            .time(data.getCreateTime())
                            .build();
                }
                else {
                    Toast.makeText(UpdateActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show();
                    finishAfterTransition();
                }
            }
        });
    }

    /**
     * 更新数据
     */
    public void update(AccountUpdateDto dto) {
        if (dto != null) {
            AccountRequester.updateAccount(this, dto, new AfterExecutor<AccountDto>() {
                @Override
                public void execute(Result<AccountDto> result) {
                    if (result.isSuccess()) {
                        DataHandler.putData(dto);
                    }
                }
            });
        }
    }


    /**
     * android 4.4以上的处理方式
     */
    private String handleImageOnKitKat(Uri uri) {
        String imagePath = null;
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content: //downloads/public_downloads"), Long.parseLong(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是file类型的Uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        return imagePath;
    }

    //  获取路径
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过Uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
            if (index == -1) {
                return null;
            }
            path = cursor.getString(index);
            cursor.close();
        }
        return path;
    }
}